﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public class PeopleExport
{
  /// <summary>
  /// Exports the lot as a TSV file
  /// </summary>
  public static string DoExport(string whereClause)
  {
    using (SqlConnection conn = Conn.GetOpened())
    {
      string sql = String.Format(
        "select * from people where {0} order by last_name,first_name,email,id",
        whereClause);
      SqlCommand cmd = new SqlCommand(sql, conn);
      SqlDataReader rdr = cmd.ExecuteReader();
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < rdr.FieldCount; i++) // header row
        sb.Append(rdr.GetName(i)).Append('\t');
      sb.AppendLine();
      while (rdr.Read())
      {
        for (int i = 0; i < rdr.FieldCount; i++)
          sb.Append(CsvField(rdr.GetValue(i).ToString())).Append('\t');
        sb.AppendLine();
      }
      return sb.ToString();
    }
  }

  /// <summary>
  /// Converts a string into a csv-safe field
  /// </summary>
  public static string CsvField(string f)
  {
    return (f.Contains(',') || f.Contains("\"")) ?
      "\"" + f.Replace("\"", "\"\"") + "\"" :
      f;
  }
}
